package com.gong.gongcloudpicture1.manager;

import cn.hutool.core.io.FileUtil;
import com.gong.gongcloudpicture1.config.CosClientConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 通用的文件上传以及文件下载的工具
 */
@Component
public class CosManager {


    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;


    /**
     * 简单上传, 查看cos api技术文档
     * @param key 这个key的意思是, 要将文件存储在哪一个位置, 就相当于将文件保存在哪个位置是一个意思, 每一个key对应着一个文件, 是唯一的
     * @param file
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }


    /**
     * 下载文件
     * @param key 目标文件的key, 唯一标识
     * @return
     */
    public COSObject getObject(String key) {
        GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
        return cosClient.getObject(getObjectRequest);
    }


    /**
     * 上传图片并解析图片信息 (需要利用 腾讯云 的 数据万象, 如果没有开通, 需要开通后使用, 否则报错)
     * @param key 目标文件key 路径
     * @param file 上传的文件
     * @return
     */
    public PutObjectResult putPictureObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        //对图片进行处理, 获取图片的基本信息
        PicOperations picOperations = new PicOperations();
        // 1表示返回原图信息
        picOperations.setIsPicInfo(1);
        List<PicOperations.Rule> picOperationsList = new ArrayList<>();
        //图片压缩 (转换成webp格式)
        //构造图片的操作规则
        PicOperations.Rule picOperationsRule = new PicOperations.Rule();
        String webpKey = FileUtil.mainName(key) + ".webp";
        picOperationsRule.setFileId(webpKey);
        picOperationsRule.setBucket(cosClientConfig.getBucket());
        picOperationsRule.setRule("imageMogr2/format/webp");
        picOperationsList.add(picOperationsRule);
        //将构造参数传入
        picOperations.setRules(picOperationsList);
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }


}
